#!/usr/bin/env bash

set -euo pipefail

function fix_dir_stdin {
  sed -e "s!$DIR!/home/dark/app!g"
}

function fix_dir_stdout {
  sed -e "s!/home/dark/app!$DIR!g" | sed -e "s!/home/dark/.opam/.*/bin!$DIR/scripts!g"
}

# Replace any filenames with the in-container filenames (stdin)
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
# shellcheck disable=SC2124
ARGS=()
for arg in "$@"
do
  ARGS+=( "$(echo "$arg" | fix_dir_stdin)" )
done

if [[ -v CURRENTLY_REBUILDING_DOCKER ]];
then
  NAME=$(docker ps --last 2 --filter "name=dark-builder" --filter status=running --quiet | tail -n 1)
else
  NAME=$(docker ps --last 1 --filter "name=dark-builder" --filter status=running --quiet)
  # If the dev container isn't running, try the vscode container
  if [[ "${NAME}x" == "x" ]]; then
    NAME=$(docker ps --last 1 --filter "label=dark-dev-container" --filter status=running --quiet)
  fi
fi

if [[ "$NAME" == "" ]]; then
  echo "No container name. Is the container not running?"
  exit 1
fi

gid="$(id -g)"
# Below is max($gid, 1000); on OS X, the user's group might be staff, with
# gid=20, which conflicts with ubuntu group dialout.
gid=$((gid > 1000 ? gid : 1000))
USER="$(id -u):$gid"

if [ -t 0 ] ;
then
  docker exec -it "${NAME}" "${ARGS[@]}" ;
else
  # Replace any in-container filenames with host filenames (stdout + stderr)
  { cat <&0 | fix_dir_stdin | docker exec -i "${NAME}" "${ARGS[@]}" 2>&1 1>&3 3>&- | fix_dir_stdout; } 3>&1 1>&2 | fix_dir_stdout
fi
